/**    
 * @{#} CreateCostActivity.java Create on 2014-6-10 下午1:35:57    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.util.HashMap;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.o.app.util.OUtil;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.umeng.analytics.MobclickAgent;

@SuppressLint("InflateParams")
public class CreateCostActivity extends BasicActivity {

	private String qid;
	private final String txt_yue = "余额支付（账户余额%s元）",
			txt_chongzhi = "充值并支付剩余金额（%s元）";

	private TextView text_question_name, text_date;

	private EditText edit_cost;

	private Button btn_pay_for_yue, btn_pay_for_chongzhi;

	private int currentYue;

	private JSONObject question;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_cost);

		init();
		setNavTitle("创建悬赏");

		qid = getIntent().getStringExtra(Constant.IDENTITY_KEY);

		text_question_name = (TextView) findViewById(R.id.text_question_name);
		text_date = (TextView) findViewById(R.id.text_date);
		edit_cost = (EditText) findViewById(R.id.edit_cost);
		btn_pay_for_yue = (Button) findViewById(R.id.btn_pay_for_yue);
		btn_pay_for_chongzhi = (Button) findViewById(R.id.btn_pay_for_chongzhi);

		HashMap<String, Object> paramsQuestion = new HashMap<String, Object>();
		paramsQuestion.put(Constant.PARAM_API, "Question.Get");
		paramsQuestion.put("qids", qid);
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						if (!CommonUtility.isNull(o)) {
							JSONObject object = (JSONObject) o;
							try {
								if (CommonUtility.response200(object)) {
									question = object.getJSONArray(
											Constant.JSON_PARAM_RES)
											.getJSONObject(0);
									object = question.getJSONObject("Question");
									text_question_name.setText("问题："
											+ object.getString("Content"));
									text_date.setText("提问时间："
											+ CommonUtility.formatDate(object
													.getString("CreateTime"),
													0, 16));
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}), paramsQuestion);

		HashMap<String, Object> paramsYue = new HashMap<String, Object>();
		paramsYue.put(Constant.PARAM_API, "Account.Get");
		paramsYue.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						if (!CommonUtility.isNull(o)) {
							JSONObject object = (JSONObject) o;
							try {
								if (CommonUtility.response200(object)) {
									currentYue = object
											.getInt(Constant.JSON_PARAM_RES);
									btn_pay_for_yue.setText(String.format(
											txt_yue, currentYue));
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}), paramsYue);

		edit_cost.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence txt, int arg1, int arg2,
					int arg3) {
				if (CommonUtility.isNull(txt)) {
					txt = "0";
				}
				float cost = Float.parseFloat(txt.toString());
				if (cost < 0 || cost > 10000) {
					CommonUtility.tip(activity, "请输入1-10000之间的数字");
					edit_cost.setText(null);
					return;
				}
				if (cost > currentYue) {
					btn_pay_for_chongzhi.setVisibility(View.VISIBLE);
					btn_pay_for_chongzhi.setText(String.format(txt_chongzhi,
							cost - currentYue));
				} else {
					btn_pay_for_chongzhi.setVisibility(View.GONE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});
	}

	public void onClick(View view) {
		super.onClick(view);
		int id = view.getId();
		if (id == R.id.btn_pay_for_yue) {
			if (!btn_pay_for_chongzhi.isShown()) {
				pay();
			}
		} else if (id == R.id.btn_pay_for_chongzhi) {
			pay();
		}
	}

	void pay() {
		final String cost = edit_cost.getText().toString();
		if (!CommonUtility.isNull(cost) && Integer.parseInt(cost) > 0) {
			if (currentYue == 0) {
				Intent intent = new Intent(activity, ChongzhiActivity.class);
				intent.putExtra(Constant.IDENTITY_KEY, cost);
				startActivity(intent);
			} else {
				// 检查是否初始化过支付密码
				RequestTaskIntercept.requestIntercept(activity,
						Constant.URL.REQUEST, new RequestHandler(activity,
								new HandlerCallback() {

									@Override
									public void callback(Object o) {
										if (!CommonUtility.isNull(o)) {
											try {
												JSONObject object = (JSONObject) o;
												boolean isInit = object
														.getBoolean(Constant.JSON_PARAM_RES);
												if (isInit) {
													View v = LayoutInflater
															.from(activity)
															.inflate(
																	R.layout.view_pay_page,
																	null);
													TextView text_after_pay = (TextView) v
															.findViewById(R.id.text_after_pay);
													final EditText edit_pay_password = (EditText) v
															.findViewById(R.id.edit_pay_password);

													int c = Integer
															.parseInt(cost);
													if (c - currentYue > 0) {
														c = currentYue;
													}
													text_after_pay
															.setText("支付后账户余额:"
																	+ (currentYue - c)
																	+ "元");
													OAlert alert = new OAlert(
															getContext());
													// alert.setOK("确认");
													// alert.setCancel("取消");
													alert.setTitle("您即将以账户余额进行支付：");
													alert.setContentView(v);
													alert.show();
													alert.setListener(new OAlertListener() {

														@Override
														public boolean onOK(
																OAlert alert) {
															String password = edit_pay_password
																	.getText()
																	.toString();
															if (!CommonUtility
																	.isNull(password)) {
																HashMap<String, Object> params = new HashMap<String, Object>();
																params.put(
																		Constant.PARAM_API,
																		"Question.Set");
																params.put(
																		Constant.PARAM_TOKEN,
																		GlobalSettings.sToken);
																params.put(
																		"Cost",
																		cost);
																params.put(
																		"PayPwd",
																		OUtil.md5(password));
																params.put(
																		"qid",
																		qid);
																RequestTaskIntercept
																		.requestIntercept(
																				activity,
																				Constant.URL.REQUEST,
																				new RequestHandler(
																						activity,
																						new HandlerCallback() {

																							@Override
																							public void callback(
																									Object o) {
																								if (!CommonUtility
																										.isNull(o)) {
																									JSONObject object = (JSONObject) o;
																									try {
																										if (CommonUtility
																												.response200(object)) {
																											Intent intent = new Intent(
																													Constant.RECIVER_QUESTION);
																											intent.putExtra(
																													Constant.IDENTITY_KEY_1,
																													true);
																											sendBroadcast(intent);
																											OAlert alert = new OAlert(
																													getContext());
																											alert.setOK("确认");
																											alert.setTitle("创建悬赏问题成功");
																											alert.show();
																											alert.setListener(new OAlertListener() {

																												@Override
																												public boolean onOK(
																														OAlert alert) {
																													CommonUtility
																															.finishActivityFromName(CreateQuestionSuccessfullyActivity.class
																																	.getSimpleName());
																													finish();
																													return false;
																												}

																												@Override
																												public boolean onCancel(
																														OAlert alert) {
																													return false;
																												}
																											});
																										}
																									} catch (Exception e) {
																										e.printStackTrace();
																									}
																								}
																							}

																						}),
																				params);
															} else {
																return true;// 没有输入
															}
															return false;
														}

														@Override
														public boolean onCancel(
																OAlert alert) {
															return false;
														}
													});
												} else {
													if (CommonUtility
															.isNull(GlobalSettings.sUser.Mobile)) {
														OAlert alert = new OAlert(
																getContext());
														alert.setOK("确认");
														alert.setCancel("取消");
														alert.setTitle(R.string.s_init_mobile);
														alert.show();
														alert.setListener(new OAlertListener() {

															@Override
															public boolean onOK(
																	OAlert alert) {
																Intent intent = new Intent(
																		activity,
																		RegisterFirstStepActivity.class);
																intent.putExtra(
																		Constant.IDENTITY_KEY_1,
																		Constant.TYPE_UPDATE_MOBILE);
																startActivity(intent);
																return false;
															}

															@Override
															public boolean onCancel(
																	OAlert alert) {
																return false;
															}
														});
													} else {
														OAlert alert = new OAlert(
																getContext());
														alert.setOK("确认");
														alert.setCancel("取消");
														alert.setTitle(R.string.s_init_paypassword);
														alert.show();
														alert.setListener(new OAlertListener() {

															@Override
															public boolean onOK(
																	OAlert alert) {
																try {
																	CommonUtility
																			.confirmSendCode(
																					activity,
																					GlobalSettings.sUser.Mobile,
																					Constant.TYPE_RESET_PAY_PASSWORD);
																} catch (Exception e) {
																	e.printStackTrace();
																}
																return false;
															}

															@Override
															public boolean onCancel(
																	OAlert alert) {
																return false;
															}
														});
													}
												}
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									}
								}), CommonUtility.params(new String[] {
								Constant.PARAM_API, Constant.PARAM_TOKEN },
								new String[] { "Account.CheckInitPayPwd",
										GlobalSettings.sToken }));
			}

		} else {
			CommonUtility.tip(activity, "请输入大于0的有效的数字");
		}
	}
	
	
/*	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(getContext());
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/
}
